package com.white.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.white.annotation.ViewInc;
import com.white.bean.Article;
import com.white.bean.Comment;
import com.white.bean.ThumbsUp;
import com.white.bean.User;
import com.white.mapper.ThumbsUpMapper;
import com.white.service.ArticleService;
import com.white.service.CommentService;
import com.white.service.UserService;
import com.white.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ArticleController {

    @Autowired
    ArticleService articleService;
    @Autowired
    UserService userService;
    @Autowired
    CommentService commentService;
    @Autowired
    ThumbsUpMapper thumbsUpMapper;

    @Autowired
    Utils utils;

    @GetMapping("/getArticleList")
    @ResponseBody
    public List<Article> getArticleList() {
        return articleService.list();
    }

    /**
     * 通过分类ID获取t推荐文章
     * @param classifyId
     * @return
     */
    @GetMapping("/getArticleList/{classifyId}")
    @ResponseBody
    public List<Article> getArticleListByClassifyId(@PathVariable("classifyId") Long classifyId) {
        return articleService.getArticleListByClassifyId(classifyId);
    }

    @GetMapping("/getLikeArticle")
    @ResponseBody
    public List<Article> getLikeArticle(@CookieValue(UserController.LOGIN_USER_ID) Long userId) {
        return articleService.getLikeArticleByUserId(userId);
    }

    /**
     * 通过用户id获取点赞文章
     * @param userId
     * @return
     */
    @GetMapping("/getLikeArticle/{userId}")
    @ResponseBody
    public List<Object> getLikeArticleByUserId(@PathVariable("userId") Long userId) {
        /*获取点赞信息*/
        List<ThumbsUp> thumbs = thumbsUpMapper.getLikeByUserId(userId);
        List<Object> thumbList = new ArrayList<>();
        for (ThumbsUp thumb : thumbs) {
            Map<String, Object> map = new HashMap<>();
            Article article = articleService.getById(thumb.getBeThumbsUpId());
            map.put("like", thumb);
            map.put("article", article);
            thumbList.add(map);
        }
        return thumbList;
    }

    @GetMapping("/getCommentArticle/{userId}")
    @ResponseBody
    public List<Object> getCommentArticleByUserId(@PathVariable("userId") Long userId) {

        List<Comment> comments = commentService.getCommentByUserId(userId);
        List<Object> commentList = new ArrayList<>();
        for (Comment comment : comments) {
            Map<String, Object> map = new HashMap<>();
            Article article = articleService.getById(comment.getArticleId());
            map.put("comment", comment);
            map.put("article", article);
            commentList.add(map);
        }
        return commentList;
    }

    @GetMapping("/listArticle")
    public String listArticle() {
        return "listArticle";
    }

    @GetMapping("articleDetail/{articleId}")
    public String articleDetail() {
        return "articleDetail";
    }


    @GetMapping("getArticlesByUserId/{userId}")
    @ResponseBody
    public List<Article> getArticlesByUserId(@PathVariable("userId") int userId) {
        QueryWrapper<Article> query = new QueryWrapper<>();
        query.eq("userId", userId);
        return articleService.list(query);
    }

    /**
     * 通过ID获取文章
     * @param articleId
     * @return
     */
    @GetMapping("/article/{articleId}")
    @ResponseBody
    @ViewInc
    public Map<String, Object> getArticleById(@CookieValue(UserController.LOGIN_USER_ID) Long userId,
                                              @PathVariable("articleId") Long articleId) {
        Map<String, Object> map = new HashMap<>();
        Article article = articleService.getById(articleId);
        map.put("userId", userId);
        map.put("articleId", articleId);
        map.put("article", article);
        User user = userService.getById(article.getUserId());
        map.put("user", user);
        List<Comment> commentList = commentService.getCommentByArticleId(article.getArticleId());
        List<Object> comments = new ArrayList<>();
        for (Comment comment : commentList) {
            Map<String, Object> m = getCommentInfo(userId, comment);
            /*获取评论的回复*/
            List<Comment> replyList = commentService.getReplies(comment.getCommentId());
            /*获取回复的用户列表*/
            m.put("replies", getCommentInfo(userId, replyList));
            comments.add(m);
        }
        map.put("comments", comments);
        return map;
    }

    public Map<String, Object> getCommentInfo(@CookieValue(UserController.LOGIN_USER_ID) Long userId,
                                              Comment comment) {
        Map<String, Object> ans = new HashMap<>();
        /*获取评论的喜欢状态*/
        ThumbsUp thumbsUp = thumbsUpMapper.isLikeComment(userId, comment.getCommentId(), ThumbsUpController.COMMENT_TYPE);
        ans.put("isLikeComment", thumbsUp != null);
        /*获取评论对应的用户*/
        User u = userService.getById(comment.getUserId());
        ans.put("user", u);
        ans.put("comment", comment);
        return ans;
    }

    public List<Object> getCommentInfo(@CookieValue(UserController.LOGIN_USER_ID) Long userId,
                                       List<Comment> list) {
        List<Object> ans = new ArrayList<>();
        for (Comment reply : list) {
            Map<String, Object> replyMap = getCommentInfo(userId, reply);
            ans.add(replyMap);
        }
        return ans;
    }

    @GetMapping("/listRecommendArticle")
    public String listRecommendArticle() {
        return "listRecommendArticle";
    }


    @GetMapping("/getRecommendArticle")
    @ResponseBody
    public List<Article> getRecommendArticle(@CookieValue(UserController.LOGIN_USER_ID) Long userId) {
        /*用户未登录，返回热门文章*/
        if (userId == 0) {
            return getHotArticle();
        }
        /*用户已登录，返回推荐文章,为防止新注册用户推荐文章为空，返回热门文章*/
        List<Article> articles = articleService.getRecommendArticle(userId);
        return articles.size() == 0 ? getHotArticle() : articles;
    }



    @GetMapping("/getRecommendArticle/{page}/{limit}")
    @ResponseBody
    public List<Article> getRecommendArticle(@CookieValue(UserController.LOGIN_USER_ID) Long recommendUserId,
                                      @PathVariable("page") int page,
                                      @PathVariable("limit") int limit) {
        List<Article> recommendArticles = articleService.getRecommendArticleByPage(recommendUserId, page, limit);
        /*若推荐文章为空，获取热门文章*/
        if (recommendArticles == null || recommendArticles.size() == 0) {
            return articleService.getHotArticleByPage(page, limit);
        }
        return recommendArticles;
    }


    @GetMapping("/getHotArticle")
    @ResponseBody
    public List<Article> getHotArticle() {
        return articleService.getHotArticle();
    }

    /**
     * 推荐文章
     * @return
     */
    @GetMapping("/recommend")
    public String recommend() {
        return "recommend";
    }

    @GetMapping("/userArticle")
    public String userArticle() {
        return "userArticle";
    }

    @GetMapping("/likeArticle")
    public String likeArticle() {
        return "likeArticle";
    }

    @GetMapping("/commentArticle")
    public String commentArticle() {
        return "commentArticle";
    }



    @GetMapping("/getArticlePage/{page}/{limit}")
    @ResponseBody
    public Object getArticlePage(@PathVariable("page") int page,
                              @PathVariable("limit") int limit) {
        Page<Article> articlePage = new Page<>(page, limit);
        return articleService.page(articlePage, null);
    }



    @GetMapping("/deleteArticleById/{id}")
    @ResponseBody
    public void deleteArticleById(@PathVariable("id") int id) {
        articleService.removeById(id);
    }


    @PostMapping("/updateArticle")
    @ResponseBody
    public void updateArticle(@RequestParam("item") String item) {
        Article article = utils.jsonToEntry(Article.class, item);
        articleService.updateById(article);
    }

    @GetMapping("/product")
    public String product() {
        return "product";
    }

    /**
     * 发布文章
     * @param userId 用户id
     * @param classifyId 分类id
     * @param title 标题
     * @param description 描述
     * @param content 内容
     * @return
     */
    @PostMapping("/product")
    @ResponseBody
    public boolean product(@CookieValue(UserController.LOGIN_USER_ID) Long userId,
                        @RequestParam("classifyId") Long classifyId,
                        @RequestParam("title") String title,
                        @RequestParam("description") String description,
                        @RequestParam("content") String content) {

        Article article = new Article(userId, classifyId, title, description, content, content.length());
        try{
            articleService.save(article);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取推荐文章的标题
     * @param recommendUserId 推荐用户iid
     * @param page 页码
     * @param limit 条数
     * @return
     */
    @GetMapping("/getRecommendKw/{page}/{limit}")
    @ResponseBody
    public List<String> getRecommendKw(@CookieValue(UserController.LOGIN_USER_ID) Long recommendUserId,
                                             @PathVariable("page") int page,
                                             @PathVariable("limit") int limit) {
        List<String> ans = new ArrayList<>();
        List<Article> articles = getRecommendArticle(recommendUserId, page, limit);
        for (Article article : articles) {
            ans.add(article.getTitle());
        }
        return ans;
    }
}
